package com.topisv.tms.service.work;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.log.OrderLog;
import com.topisv.tms.entity.work.WorkLog;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.repository.log.OrderLogDao;
import com.topisv.tms.repository.work.WorkLogDao;
import com.topisv.tms.repository.work.WorkOrderDao;
import com.topisv.tms.repository.work.WorkTaskDao;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.base.BaseService;
import com.topisv.tms.service.vo.invoice.InvoiceRequest;
import com.topisv.tms.service.vo.invoice.InvoiceReturnModel;
import com.topisv.tms.tools.TransferHelper;

@Component
public class InvoicePrintService extends BaseService {
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private WorkTaskDao workTaskDao;
	@Autowired
	private OrderLogDao orderLogDao;
	@Autowired
	private WorkLogDao workLogDao;
	@Autowired
	private AccountService accountService;
	@Autowired
	private EdiOrderService ediOrderService;
	
	@Transactional(readOnly = false)
	public void updateInvoice(InvoiceReturnModel invoiceReturn){
		Date now = new Date();
		User curUser = this.accountService.findUserByJobuuid(invoiceReturn.getUser().jobuuid);
		String orderNO = invoiceReturn.getOrderNO();
		WorkOrder workOrder = workOrderDao.loadByOrderno(orderNO);
		String invoiceNo = StringUtils.isBlank(invoiceReturn.getInvoiceNo()) ? null : invoiceReturn.getInvoiceNo();
		StringBuilder logInfo = new StringBuilder(); 
		if ("0".equals(invoiceReturn.getReturnCode())) {// 开票成功
			// 标示该订单已开票
			workOrderDao.updateInvoiceNo(invoiceNo,invoiceReturn.getInvoiceOperate(), workOrder.getId());
			if("1".equals(invoiceReturn.getDeleteFlg())){
				logInfo.append(curUser.getRealname()).append("已作废发票:").append(workOrder.getInvoiceNo()).append("\t");
			}
			if(invoiceNo != null){
				logInfo.append(curUser.getRealname()).append("已打印发票:").append(invoiceNo);
			}
		} else {// 开票失败
			// 记录日志。
			logInfo.append(curUser.getRealname()).append("打印发票失败.").append("错误码：").append(invoiceReturn.getReturnCode()).append("错误信息：").append(invoiceReturn.getMsg());
		}
		//添加订单日志
		OrderLog orderlog=new OrderLog(workOrder.getOrder().getOrdeno(),
				workOrder.getCustomerCode(), 
				"18", //操作类型 （1.创建拣货批次 2.创建拣货任务 3.修正拣货信息 4.拣货完成 5.包装完成 6.发货完成 7.签收完成 8.异常登记 9.已打印单据）
				curUser,
				now,
				null, 
				logInfo.toString());
		orderLogDao.save(orderlog);
		// 如果这一批次都已打印发票，标记批次已打印
		List<WorkOrder> unprintedList = workOrderDao.loadInvoiceUnprintedList(workOrder.getTaskCode());
		if (unprintedList.isEmpty()) {
			workTaskDao.updateInvoiceStatus("1", workOrder.getTaskCode());
			// 作业日志
			WorkLog workLog = new WorkLog(workOrder.getBatchCode(), "12", "执行打印快递单据（" + workOrder.getTaskCode() + "）", now, curUser);
			workLogDao.save(workLog);
		}
	}
	
	/**
	 * 构建开票的xml
	 * @param request
	 * @return String
	 */
	public List<String> buildInvoiceXml(InvoiceRequest request){
		String[] orderNos = request.getOrderNo().split(":");
		List<String> xmls = new ArrayList<String>(orderNos.length);
		for (int i = 0; i < orderNos.length; i++) {
			String orderno = orderNos[i];
			EdiOrder order = ediOrderService.findByOrderNoDetail(orderno);
			xmls.add(TransferHelper.buildInvoiceXml(order, request));
		}
		return xmls;
	}
	
	/**
	 * 根据size分割订单号
	 * @param taskCode
	 * @param size
	 * @return
	 */
	public String spliteInvoiceOrder(String taskCode, int size) {
		List<WorkOrder> orders = workOrderDao.loadInvoiceUnprintedList(taskCode);
		StringBuilder sb = new StringBuilder();
		for (int i = 0, length = orders.size(); i < length; i++) {
			WorkOrder order = orders.get(i);
			sb.append(order.getOrder().getOrdeno()).append(":");
			if (i != 0 && i % size == 0) {
				sb.append(";");
			}
		}
		return sb.append(";finish").toString();
	}
}
